<template>
	<view class="setting">
		<u-cell-group>
			<u-cell title="头像" isLink @click="openActionSheet('avatar')">
				<u-avatar slot="value" :src="userInfo.avatar[0].url" />
			</u-cell>
			<u-cell title="昵称" :value="userInfo.userName" isLink @click="openPopup('userName')" />
			<u-cell title="性别" :value="userInfo.sex == 'M' ? '男' : '女'" isLink @click="openActionSheet('sex')" />
			<u-cell title="生日" isLink :value="userInfo.birthday|setTime" @click="openSettingDatetimePicker" />
			<u-cell title="绑定邮箱" :value="userInfo.email" isLink @click="openActionSheet('email')" />
			<u-cell title="修改密码" value="******" isLink @click="openActionSheet('password')" />
			<u-cell title="个性签名" isLink @click="openPopup('descText')">
				<view style="width: 300rpx;color: #606266;" class="u-line-2" slot="value">
					{{ userInfo.descText || '未填写' }}
				</view>
			</u-cell>
		</u-cell-group>
		<view class="setting-menu">
			<u-button text="退出登录" iconColor="#fff" @click="loginOut" />
		</view>
		<u-upload ref="uploadAvatar" @afterRead="afterRead" name="file" multiple :maxCount="1" style="display: none;" />
		<u-action-sheet :actions="settingActionSheet.handleMenuList" cancelText="取消" :show="settingActionSheet.visible"
			round="20rpx" :description="settingActionSheet.description" closeOnClickOverlay
			@close="closeSettingActionSheet" @select="selectSettingActionSheet" />
		<u-popup :show="settingPopup.visible" mode="center" round="8" @close="closeSettingPopup">
			<view class="settingPopup">
				<view class="flexCenter fs16 mb10">{{ settingPopup.title }}</view>
				<!-- 修改名称 -->
				<u--input v-if="settingPopup.type === 'userName'" placeholder="请输入用户昵称" border="surround"
					v-model="settingPopup.userName" />
				<!-- 更换邮箱 -->
				<view v-if="settingPopup.type === 'email'" class="">
					<view class="flex">
						<text class="mr5">原邮箱地址：</text>
						<text>{{ userInfo.email || '未绑定邮箱地址' }}</text>
					</view>
					<u-gap height="15" />
					<u-input v-model="settingPopup.code" maxlength="4" border="surround" type="text"
						prefixIconStyle="color: #fff;font-size: 22px;line-height: 22px;" placeholder="输入邮箱验证码" typ
						:spellcheck="false">
						<text slot="suffix" style="color: #2b85e4;" @click="sendCode">{{ settingPopup.codeText }}</text>
					</u-input>
					<u-gap height="15" />
					<u--input placeholder="请输入新的邮箱地址" border="surround" v-model="settingPopup.newEmail" />
				</view>
				<!-- 个性签名 -->
				<u--textarea v-if="settingPopup.type === 'descText'" v-model="settingPopup.descText" placeholder="请输入签名"
					autoHeight />
				<!-- 重置密码 -->
				<view v-if="settingPopup.type === 'password'" class="">
					<view class="flex">
						<text class="mr5">原邮箱地址：</text>
						<text>{{ userInfo.email || '未绑定邮箱地址' }}</text>
					</view>
					<u-gap height="15" />
					<u-input v-model="settingPopup.code" maxlength="4" border="surround" type="text"
						prefixIconStyle="color: #fff;font-size: 22px;line-height: 22px;" placeholder="输入邮箱验证码" typ
						:spellcheck="false">
						<text slot="suffix" style="color: #2b85e4;" @click="sendCode">{{ settingPopup.codeText }}</text>
					</u-input>
					<u-gap height="15" />
					<u--input placeholder="请输入新的密码" border="surround" v-model="settingPopup.password" />
				</view>
				<u-gap height="15" />
				<u-button text="保存" @click="saveSettingPopup" />
			</view>
		</u-popup>
		<u-datetime-picker ref="settingDatetimePicker" :show="settingDatetimePicker.visible" :formatter="formatter"
			v-model="settingDatetimePicker.value" mode="date" :maxDate="Number(new Date())"
			@cancel="cancelSettingDatetimePicker" @confirm="confirmSettingDatetimePicker" />
		<u-code ref="settingCode" :seconds="300" uniqueKey="settingCode" keepRunning @change="settingCodeChange" />
	</view>
</template>

<script>
	import {
		base_api_URL
	} from '@/config/index'
	import {
		mapGetters
	} from 'vuex'
	import {
		parseTime
	} from '@/utils/util.js'
	export default {
		name: "Setting", // 首页页面
		options: {
			styleIsolation: "shared"
		}, // 父组件设置 options.styleIsolation 可穿透子组件，以及页面
		filters: {
			setTime(value) {
				return parseTime(value, '{y}-{m}-{d}')
			}
		},
		data() {
			return {
				settingActionSheet: {
					description: '',
					visible: false,
					handleMenuList: [], // 动态操作菜单数据
					handleMenuData: [{
							name: '查看大图',
							key: 'avatar',
							description: '更换头像'
						},
						{
							name: '上传头像',
							key: 'avatar',
							description: '更换头像'
						},
						{
							name: '男',
							key: 'sex',
							description: '修改性别'
						}, {
							name: '女',
							key: 'sex',
							description: '修改性别'
						},
						{
							name: '更换邮箱',
							key: 'email',
							description: '邮箱'
						},
						{
							name: '修改密码',
							key: 'password',
							description: '密码'
						},
					]
				},
				settingPopup: { // 设置弹出层
					visible: false,
					type: '',
					userName: '',
					newEmail: '', // 新的邮箱地址
					code: '', // 验证码
					codeText: "发送验证码",
					descText: '', // 个性签名
					password: ''
				},
				settingDatetimePicker: {
					visible: false,
					value: Number(new Date())
				}
			};
		},
		computed: {
			...mapGetters(['userInfo'])
		},
		onReady() {
			// 微信小程序需要用此写法
			this.$refs.settingDatetimePicker.setFormatter(this.formatter)
		},
		methods: {
			// 验证码倒计时期间，每秒触发一次
			settingCodeChange(text) {
				this.settingPopup.codeText = text
			},
			// 发送验证码
			async sendCode() {
				if (!this.$refs.settingCode.canGetCode) { // false时为已发送验证码状态
					return
				}
				if (!this.userInfo.email) {
					// this.showToast('请绑定邮箱')
					return
				}
				const {
					code
				} = await this.$verify.emailVerify({
					email: this.userInfo.email
				})
				if (code === 0) {
					this.showToast('验证码已发送')
					this.$refs.settingCode.start()
				}
			},
			// 打开日期选择器
			openSettingDatetimePicker() {
				this.settingDatetimePicker = {
					visible: true,
					value: parseInt(this.userInfo.birthday)
				}
			},
			// 确定选择日期回调
			confirmSettingDatetimePicker() {
				this.userModify({
					birthday: this.settingDatetimePicker.value
				})
			},
			// 关闭日期选择器回调
			cancelSettingDatetimePicker() {
				this.settingDatetimePicker = {
					visible: false,
					value: Number(new Date())
				}
			},
			// 日期选择器格式化
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			// 弹出层保存
			saveSettingPopup() {
				let bool = true
				switch (this.settingPopup.type) {
					case 'email':
						if (this.userInfo.email && this.settingPopup.code && this.settingPopup.newEmail) bool = false
						break
					case 'password':
						if (this.userInfo.email && this.settingPopup.code && this.settingPopup.password) bool = false
						break
					case 'userName':
						if (this.settingPopup.userName) bool = false
						break
					case 'descText':
						if (this.settingPopup.descText) bool = false
						break
				}
				if (bool) {
					this.showToast('未填写完成')
					return
				}
				switch (this.settingPopup.type) {
					case 'email':
						this.userCheckEmail()
						break
					case 'password':
						this.userResetPass()
						break
					default:
						this.userModify({
							userName: this.settingPopup.userName ? this.settingPopup.userName : undefined,
							descText: this.settingPopup.descText ? this.settingPopup.descText : undefined
						})
						break
				}
			},
			// 重置密码
			async userResetPass() {
				const {
					code
				} = await this.$user.userResetPass({
					email: this.userInfo.email,
					code: this.settingPopup.code,
					password: this.settingPopup.password
				})
				if (code === 0) {
					this.showToast('修改成功')
					this.closeSettingPopup()
					this.$store.dispatch("user/GetInfo")
				}
			},
			// 更换绑定邮箱
			async userCheckEmail() {
				const {
					code
				} = await this.$user.userCheckEmail({
					email: this.userInfo.email,
					newEmail: this.settingPopup.newEmail,
					code: this.settingPopup.code
				})
				if (code === 0) {
					this.showToast('修改成功')
					this.closeSettingPopup()
					this.$store.dispatch("user/GetInfo")
				}
			},
			// 关闭弹出层
			closeSettingPopup() {
				this.settingPopup = { // 设置弹出层
					visible: false,
					type: '',
					userName: '',
					newEmail: '', // 新的邮箱地址
					code: '', // 验证码
					codeText: "发送验证码",
					descText: '',
					password: ''
				}
			},
			// 打开弹出层
			openPopup(type) {
				this.settingPopup = { // 设置弹出层
					visible: true,
					type,
					userName: this.userInfo.userName,
					newEmail: '', // 新的邮箱地址
					code: '', // 验证码
					codeText: "发送验证码",
					descText: this.userInfo.descText,
					password: ''
				}
				switch (type) {
					case 'userName':
						this.settingPopup.title = '修改昵称'
						break
					case 'email':
						this.settingPopup.title = '更换邮箱'
						break
					case 'descText':
						this.settingPopup.title = '修改签名'
						break
					case 'password':
						this.settingPopup.title = '重置密码'
						break
				}
			},
			// 文件读取后的处理函数
			afterRead(data) {
				const file = data.file[0]
				uni.uploadFile({
					url: `${base_api_URL}/upload/qiniuImage`,
					filePath: file.url,
					name: 'file',
					header: {
						token: uni.getStorageSync('chuchujie-token').value || ''
					},
					success: ({
						statusCode,
						data
					}) => {
						if (statusCode === 200 && JSON.parse(data).code === 0) {
							const res = JSON.parse(data)
							this.userModify({
								avatar: res.data.id
							})
						}
					}
				})
			},
			// 修改用户接口
			async userModify(data) {
				const {
					code
				} = await this.$user.userModify(data)
				if (code === 0) {
					this.showToast('修改成功')
					this.$store.dispatch("user/GetInfo")
					this.closeSettingPopup()
					this.closeSettingActionSheet()
					this.cancelSettingDatetimePicker()
				}
			},
			// 点击打开头像图片预览
			openPreviewImage() {
				const urls = [this.userInfo.avatar[0].url]
				uni.previewImage({
					indicator: 'number',
					loop: true,
					urls
				})
			},
			// 点击ActionSheet列表项时触发
			selectSettingActionSheet(item) {
				console.log(item)
				switch (item.name) {
					case '查看大图':
						this.openPreviewImage()
						break;
					case '上传头像':
						this.$refs.uploadAvatar.chooseFile()
						break;
					case '男':
						this.userModify({
							sex: 'M'
						})
						break
					case '女':
						this.userModify({
							sex: 'W'
						})
						break
					case '更换邮箱':
						this.openPopup('email')
						break
					case '修改密码':
						this.openPopup('password')
						break
				}
			},
			// 退出登录
			loginOut() {
				this.$store.dispatch('user/Loginout').then(() => {
					uni.navigateTo({
					  url: '/pages/login/index',
					  animationType: 'pop-in',
					  animationDuration: 200
				  })
				})
			},
			// 关闭操作菜单
			closeSettingActionSheet() {
				this.settingActionSheet.visible = false
				this.settingActionSheet.description = ''
				this.settingActionSheet.handleMenuList = []
			},
			// 打开操作菜单
			openActionSheet(target) {
				this.settingActionSheet.visible = true
				this.settingActionSheet.description = this.settingActionSheet.handleMenuData[this.settingActionSheet
					.handleMenuData.findIndex(item => item.key === target)].description
				this.settingActionSheet.handleMenuList = this.settingActionSheet.handleMenuData.filter(item => item.key ===
					target)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.setting {
		/deep/ .u-cell {
			&__body {
				background-color: #FFFFFF;

				&:active {
					background-color: rgba(0, 0, 0, .1);
				}
			}
		}

		&-menu {
			padding: 40rpx 10rpx;

			/deep/ .u-button {
				background-color: $uni-color-primary;
				color: #fff;
			}
		}
	}

	.settingPopup {
		width: 600rpx;
		padding: 40rpx 20rpx;

		/deep/ .u-button {
			background-color: $uni-color-primary;
			color: #FFFFFF;
		}
	}
</style>
